#include <unistd.h>
#include "ChatClient.hpp"

void Menu()
{
    std::cout << "***************************************" << std::endl;
    std::cout << "*****1.register  ***  2.login**********" << std::endl;
    std::cout << "*****3.logout    ***  4.exit **********" << std::endl;
    std::cout << "***************************************" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        // ./ChatClient -ip [ip]
        std::cout << "using ./ChatClient [ip]" << std::endl;
        return -1;
    }
    std::string ip;
    for(int i = 0; i < argc; i++)
    {
        if(strcmp(argv[i], "-ip") == 0 && (i + 1) < argc)
        {
            ip = argv[i + 1];
        }
    }

    if(ip.size() == 0)
    {
        LOG(ERROR, "Illegal ip , please retry start ChatClient") << std::endl;
        return -1;
    }

    UdpClient uc;

    while(1)
    {
        Menu();
        int select = -1;
        std::cout << "please enter your select: ";
        fflush(stdout);
        std::cin >> select;
        if(1 == select)
        {
            //注册的逻辑
           int ret = uc.RegistertoSvr(ip);
           if(ret < 0)
           {
               LOG(WARNING, "please retry register") << std::endl;
           }
           else if(0 == ret)
           {
               LOG(INFO, "register success! please login...") << std::endl;
           }
           uc.CloseFd();
        }
        else if(2 == select)
        {
            //登录的逻辑
            int ret = uc.LoginToSvr(ip);
            if(ret < 0)
            {
                LOG(ERROR, "please retry login") << std::endl;
            }
            else if(0 == ret)
            {
                LOG(INFO, "login success, please chatting...") << std::endl;
                while(1)
                {
                    std::string msg;
                    std::cout << "please enter your msg: ";
                    fflush(stdout);
                    std::cin >> msg;

                    uc.SendUdpMsg(msg, ip);
                    uc.RecvUdpMsg();
                }
            }
        }
        else if(3 == select)
        {
            //登出
        }
        else if(4 == select)
        {
            //退出的逻辑
            LOG(INFO, "exit chat client") << std::endl;
            exit(0);
        }
    }

    while(1)
    {
        sleep(1);
    }
    return 0;
}
